<?php
if (!defined('ABSPATH')) { exit; }

/**
 * 远程授权统一判定模块（简化模式+令牌）
 * - 统一走远程获取短期令牌（例如7天），本地缓存
 * - 服务器仅做许可证校验并签发令牌；数据本地加密存储
 */
final class WP_Spider_Remote_Auth {
    private const AUTH_ENDPOINT = 'https://zibovip.top/dingyue/secure-license-verification.php';
    private const TOKEN_OPTION = 'spider_access_token';

    /**
     * 失效本地缓存令牌：下次访问会自动重新申请
     */
    public static function invalidate_token() : void {
        delete_option(self::TOKEN_OPTION);
    }

    /**
     * 立即刷新令牌（可在激活后调用）
     */
    public static function refresh_token_now(string $feature = 'general', string $period = 'general') : array {
        self::invalidate_token();
        $licenseKey = get_option('spider_license_key') ?: '';
        return self::check($feature, $period, $licenseKey);
    }

    /**
     * 统一判定入口：若无有效令牌则请求新令牌
     * @param string $feature
     * @param string $period
     * @param array|string $extra 若为字符串则视为 license_key 保持兼容
     * @return array {success:bool, message:string, token?:string, upgrade_url?:string}
     */
    public static function check(string $feature, string $period, $extra = []) : array {
        return [ 'success' => true, 'message' => 'OK', 'token' => 'LOCAL_FREE_ACCESS' ];
    }

    /**
     * 统一强制令牌校验：today/yesterday 直接放行，其余周期要求有效令牌并通过本地安全模块验签
     * @return array{success:bool,message:string,token?:string}
     */
    public static function enforce_token(string $feature, ?string $period = null) : array {
        return [ 'success' => true, 'message' => 'OK', 'token' => 'LOCAL_FREE_ACCESS' ];
    }

    private static function getValidToken() {
        $opt = get_option(self::TOKEN_OPTION);
        if (is_array($opt) && !empty($opt['token']) && !empty($opt['expires']) && intval($opt['expires']) > time()) {
            return $opt;
        }
        return null;
    }

    private static function post($url, $body) : array {
        $resp = wp_remote_post($url, [
            'timeout' => 15,
            'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ],
            'body'    => $body,
            'sslverify' => true
        ]);
        if (is_wp_error($resp)) {
            return [ 'error' => true, 'message' => $resp->get_error_message(), 'data' => null ];
        }
        $code = wp_remote_retrieve_response_code($resp);
        $data = json_decode(trim(wp_remote_retrieve_body($resp)), true);
        if ($code !== 200) {
            return [ 'error' => true, 'message' => 'HTTP ' . $code, 'data' => $data ];
        }
        return [ 'error' => false, 'message' => '', 'data' => $data ];
    }

    private static function validate_token_local($token, $feature, $period) {
        if (empty($token) || !is_string($token)) { return false; }
        $raw = base64_decode($token, true);
        if ($raw === false) { return false; }
        $obj = json_decode($raw, true);
        if (!is_array($obj)) { return false; }
        if (empty($obj['t']) || empty($obj['exp']) || empty($obj['feat']) || empty($obj['per'])) { return false; }
        if ($obj['feat'] !== $feature) { return false; }
        // per 可为 general 或具体周期
        if (!in_array($obj['per'], array($period, 'general'), true)) { return false; }
        if (!empty($obj['alg']) && $obj['alg'] !== 'RS256') { return false; }
        if (intval($obj['exp']) < time()) { return false; }
        return true;
    }
}


